package com.shawn.service;

import android.app.ActivityManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.text.format.Formatter;
import android.widget.RemoteViews;

import com.shawn.mobliesafe.R;
import com.shawn.receiver.MyWidget;
import com.shawn.utils.TaskUtil;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class WidgetService extends Service {

    private AppWidgetManager widgetManager;
    private WidgetReceiver widgetReceiver;
    private Timer timer;
    private ScreenOffReceiver screenOffReceiver;
    private ScreenOnReceiver screenOnReceiver;

    public WidgetService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 清理进程的广播接受者
     */
    private class WidgetReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            killProcess();
        }
    }

    /**
     * 锁屏的广播接受者
     */
    private class ScreenOffReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            //清理进程
            killProcess();
            //停止更新
            stopUpdates();
        }
    }


    /**
     * 解锁的广播接受者
     */
    private class ScreenOnReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            updateWidgets();
        }
    }

    private void stopUpdates() {
        if(timer != null) {
            timer.cancel();
            timer = null;
        }
    }


    private void killProcess() {
        ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses){
            if(!runningAppProcessInfo.processName.equals(getPackageName())) {
                activityManager.killBackgroundProcesses(runningAppProcessInfo.processName);
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();


        widgetReceiver = new WidgetReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("clear.process");
        registerReceiver(widgetReceiver, intentFilter);

        screenOffReceiver = new ScreenOffReceiver();
        IntentFilter screenoffIntentfilter  = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(screenOffReceiver, screenoffIntentfilter );

        screenOnReceiver = new ScreenOnReceiver();
        IntentFilter screenOnIntentFilter   = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_SCREEN_ON);
        registerReceiver(screenOnReceiver , screenOnIntentFilter  );

        //widget的管理者
        widgetManager = AppWidgetManager.getInstance(this);
        updateWidgets();

    }

    private void updateWidgets() {
        //计数器
        timer = new Timer();
        //执行操作
        //task : 要执行操作
        //when : 延迟的时间
        //period : 每次执行的间隔时间
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                //更新操作
                //获取组件的标示
                ComponentName provider = new ComponentName(WidgetService.this, MyWidget.class);
                //获取远程布局
                //packageName : 应用的包名
                //layoutId :widget布局文件
                RemoteViews views = new RemoteViews(getPackageName(), R.layout.process_widget);
                //远程布局不能通过findviewbyid获取初始化控件
                //更新布局文件中相应控件的值
                //viewId :更新控件的id
                //text : 更新的内容
                views.setTextViewText(R.id.process_count, "正在运行软件:" + TaskUtil.getProcessCount(WidgetService.this));
                views.setTextViewText(R.id.process_memory, "可用内存:" + Formatter.formatFileSize(WidgetService.this, TaskUtil.getAvailableRam(WidgetService.this)));


                //按钮点击事件
                Intent intent = new Intent();
                intent.setAction("clear.process");
                PendingIntent pendingIntent = PendingIntent.getBroadcast(WidgetService.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                views.setOnClickPendingIntent(R.id.btn_clear, pendingIntent);
                widgetManager.updateAppWidget(provider, views);
            }
        }, 2000, 2000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopUpdates();

        if(widgetReceiver != null) {
            unregisterReceiver(widgetReceiver);
            widgetReceiver = null;
        }
        if(screenOffReceiver != null) {
            unregisterReceiver(screenOffReceiver);
            screenOffReceiver = null;
        }
        if(screenOnReceiver != null) {
            unregisterReceiver(screenOnReceiver);
            screenOnReceiver = null;
        }
    }
}
